package com.szgd.aop;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.szgd.bean.MessageBean;
import com.szgd.util.StringUtil;

@Aspect
@Component
public class ControllerErrorAspect {

	private Logger logger = Logger.getLogger(getClass());

	@Pointcut("execution(* com.szgd.controller..*.*(..))")
	public void ControllerError() {
	}
	
	@AfterThrowing(throwing = "e", pointcut = "ControllerError()")
	public void doAfterThrowing(Exception e) throws Throwable {
		// 处理完请求，返回内容
		MessageBean mb = new MessageBean();
		if(StringUtil.isNotBlank(e.getMessage())){
			mb.setErrmsg(e.getMessage());
		}else{
			String info = getExceptionInfo(e);
			mb.setErrmsg(info);
		}
		logger.error(mb.getErrmsg());
		writeContent(MessageBean.json(mb));
	}
	
	
	private void writeContent(String content) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "text/plain;charset=UTF-8");
        response.setHeader("icop-content-type", "exception");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.print(content);
        writer.flush();
        writer.close();
    }
	
	private String getExceptionInfo(Exception e){
		StringBuffer sb = new StringBuffer();
		StackTraceElement[] traceArray = e.getStackTrace();
		for(StackTraceElement trace : traceArray){
			sb.append("\tat");
			sb.append(trace);
			sb.append("\r\n");
		}
		return sb.toString();
	}
	
}